// EU Commission 抓取功能主文件
const { EuCommissionScraper } = require('./eu-commission-core');
const fs = require('fs');
const path = require('path');

// 全局变量
let euCommissionScraper = null;
let isScrapingActive = false;
let abortController = null; // 添加中断控制器

// DOM 元素引用
let progressBar, statusText, resultsContainer, logContainer;
let startBtn, stopBtn, exportBtn, browserModeToggle;

// 初始化 EU Commission 功能
function initEuCommission() {
    console.log('初始化 EU Commission 功能...');
    
    // 获取DOM元素
    progressBar = document.getElementById('eu-progress-bar');
    statusText = document.getElementById('eu-progress-text');
    resultsContainer = document.getElementById('eu-results');
    logContainer = document.getElementById('eu-log');
    
    startBtn = document.getElementById('eu-start-btn');
    stopBtn = document.getElementById('eu-stop-btn');
    exportBtn = document.getElementById('eu-export-btn');
    browserModeToggle = document.getElementById('eu-headless-switch');
    
    // 绑定事件监听器
    if (startBtn) startBtn.addEventListener('click', startEuCommissionScraping);
    if (stopBtn) stopBtn.addEventListener('click', stopEuCommissionScraping);
    if (exportBtn) exportBtn.addEventListener('click', exportEuCommissionResults);
    
    // 初始化UI状态
    updateUI('ready', '准备就绪');
    
    console.log('EU Commission 功能初始化完成');
}

// 开始抓取
async function startEuCommissionScraping() {
    if (isScrapingActive) {
        addLog('抓取已在进行中...', 'warning');
        return;
    }
    
    try {
        isScrapingActive = true;
        
        // 创建中断控制器
        abortController = new AbortController();
        const signal = abortController.signal;
        
        updateUI('running', '正在初始化浏览器...');
        addLog('开始 EU Commission 抓取任务（支持中断）', 'info');
        
        // 创建抓取器实例
        euCommissionScraper = new EuCommissionScraper();
        
        // 获取浏览器模式设置
        const headlessMode = browserModeToggle ? browserModeToggle.value === 'headless' : true;
        addLog(`浏览器模式: ${headlessMode ? '无头模式' : '可视模式'}`, 'info');
        
        // 使用可中断模式运行抓取任务（带进度回调）
         const result = await euCommissionScraper.runWithSignal(signal, headlessMode, (progress, message) => {
             updateProgress(progress, message);
             addLog(message, 'info');
         });
        
        if (result.success) {
            // 抓取成功完成
            updateUI('completed', result.message);
            displayResults(result.results);
            addLog(result.message, 'success');
        } else {
            // 抓取被中断或失败
            if (result.message.includes('中断') || result.message.includes('取消')) {
                updateUI('stopped', result.message);
                addLog(result.message, 'warning');
                // 如果有部分结果，仍然显示
                if (result.results && result.results.length > 0) {
                    displayResults(result.results);
                    addLog(`已保存 ${result.results.length} 条记录到JSON文件`, 'info');
                }
            } else {
                updateUI('error', result.message);
                addLog(result.message, 'error');
            }
        }
        
    } catch (error) {
        console.error('EU Commission 抓取失败:', error);
        updateUI('error', `抓取失败: ${error.message}`);
        addLog(`抓取失败: ${error.message}`, 'error');
    } finally {
        isScrapingActive = false;
        abortController = null;
        // runWithSignal方法会自动处理浏览器关闭，不需要手动关闭
    }
}

// 停止抓取
async function stopEuCommissionScraping() {
    if (!isScrapingActive || !abortController) {
        addLog('没有正在进行的抓取任务', 'warning');
        return;
    }
    
    try {
        addLog('收到停止信号，正在中断抓取任务...', 'warning');
        updateUI('stopping', '正在停止抓取任务...');
        
        // 发送中断信号
        abortController.abort();
        addLog('中断信号已发送，等待任务响应...', 'info');
        
        // 不需要手动调用其他方法，runWithSignal会处理所有清理工作
        
    } catch (error) {
        console.error('停止抓取时出错:', error);
        addLog(`停止抓取时出错: ${error.message}`, 'error');
        updateUI('error', '停止时发生错误');
    }
}

// 导出结果
function exportEuCommissionResults() {
    if (!euCommissionScraper || !euCommissionScraper.results || euCommissionScraper.results.length === 0) {
        addLog('没有可导出的结果', 'warning');
        return;
    }
    
    try {
        const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
        
        // 导出JSON格式
        const jsonData = euCommissionScraper.exportToJSON();
        const jsonBlob = new Blob([jsonData], { type: 'application/json' });
        downloadFile(jsonBlob, `eu-commission-results-${timestamp}.json`);
        
        // 导出CSV格式
        const csvData = euCommissionScraper.exportToCSV();
        const csvBlob = new Blob([csvData], { type: 'text/csv' });
        downloadFile(csvBlob, `eu-commission-results-${timestamp}.csv`);
        
        addLog('结果导出成功 (JSON + CSV)', 'success');
        
    } catch (error) {
        console.error('导出结果失败:', error);
        addLog(`导出结果失败: ${error.message}`, 'error');
    }
}

// 下载文件
function downloadFile(blob, filename) {
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = filename;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
}

// 更新UI状态
function updateUI(status, message) {
    if (statusText) {
        statusText.textContent = message;
        statusText.className = `status-${status}`;
    }
    
    // 更新按钮状态
    if (startBtn) startBtn.disabled = (status === 'running' || status === 'stopping');
    if (stopBtn) stopBtn.disabled = (status !== 'running' && status !== 'stopping');
    if (exportBtn) exportBtn.disabled = (status === 'running' || status === 'stopping');
    
    // 更新进度条
    if (status === 'ready' || status === 'stopped') {
        updateProgress(0, message);
    } else if (status === 'completed') {
        updateProgress(100, message);
    } else if (status === 'stopping') {
        // 停止状态保持当前进度
        if (statusText) {
            statusText.textContent = message;
        }
    }
}

// 更新进度
function updateProgress(percentage, message) {
    if (progressBar) {
        progressBar.style.width = `${percentage}%`;
        progressBar.setAttribute('aria-valuenow', percentage);
        
        // 更新进度条颜色
        progressBar.className = 'progress-bar';
        if (percentage === 100) {
            progressBar.classList.add('bg-success');
        } else if (percentage > 0) {
            progressBar.classList.add('bg-primary');
        }
    }
    
    if (statusText && message) {
        statusText.textContent = message;
    }
}

// 显示结果
function displayResults(results) {
    if (!resultsContainer) return;
    
    if (!results || results.length === 0) {
        resultsContainer.innerHTML = '<p style="text-align: center; color: #666;">未找到符合条件的数据</p>';
        return;
    }
    
    // 过滤出有效的标准数据（非错误记录）
    const validResults = results.filter(r => !r.error && r.standard && r.standardName);
    const errorResults = results.filter(r => r.error);
    
    let html = `
        <div class="results-header">
            <h4>EU Commission 抓取结果 (${results.length} 条记录)</h4>
            <div class="results-stats">
                <span class="stat-item">有效记录: ${validResults.length} 条</span>
                <span class="stat-item">错误记录: ${errorResults.length} 条</span>
            </div>
        </div>
        <div class="results-table">
            <table class="table table-striped">
                <thead>
                    <tr>
                        <th style="width: 20%;">Standard</th>
                        <th style="width: 35%;">Standard Name</th>
                        <th style="width: 15%;">Region</th>
                        <th style="width: 15%;">Date of Publication</th>
                        <th style="width: 15%;">Actions</th>
                    </tr>
                </thead>
                <tbody>
    `;
    
    // 显示有效结果
    validResults.forEach(item => {
        const urlLink = item.url ? `<a href="${item.url}" target="_blank" class="btn btn-sm btn-outline-primary">查看详情</a>` : '-';
        
        html += `
            <tr>
                <td><strong>${item.standard}</strong></td>
                <td title="${item.standardName}">${item.standardName.length > 60 ? item.standardName.substring(0, 60) + '...' : item.standardName}</td>
                <td><span class="region-badge">${item.region}</span></td>
                <td>${item.dateOfPublication || '-'}</td>
                <td>${urlLink}</td>
            </tr>
        `;
    });
    
    // 如果有错误记录，显示错误信息
    if (errorResults.length > 0) {
        html += `
            <tr class="table-warning">
                <td colspan="5"><strong>错误记录 (${errorResults.length} 条)</strong></td>
            </tr>
        `;
        
        errorResults.forEach(item => {
            html += `
                <tr class="table-danger">
                    <td>ERROR</td>
                    <td title="${item.standardName || '未知'}">${(item.standardName || '未知').length > 60 ? (item.standardName || '未知').substring(0, 60) + '...' : (item.standardName || '未知')}</td>
                    <td>${item.region || 'Europe'}</td>
                    <td>-</td>
                    <td><small class="text-danger">${item.errorMessage || '处理失败'}</small></td>
                </tr>
            `;
        });
    }
    
    html += `
                </tbody>
            </table>
        </div>
    `;
    
    resultsContainer.innerHTML = html;
    
    // 添加样式
    const style = document.createElement('style');
    style.textContent = `
        .results-header {
            margin-bottom: 20px;
            padding: 15px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border-radius: 8px;
        }
        .results-header h4 {
            margin: 0 0 10px 0;
            font-weight: 600;
        }
        .results-stats {
            display: flex;
            gap: 20px;
        }
        .stat-item {
            background: rgba(255,255,255,0.2);
            padding: 5px 12px;
            border-radius: 15px;
            font-size: 14px;
        }
        .results-table {
            background: white;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .results-table table {
            margin: 0;
        }
        .results-table th {
            background: #f8f9fa;
            font-weight: 600;
            border-bottom: 2px solid #dee2e6;
        }
        .region-badge {
            background: #e3f2fd;
            color: #1976d2;
            padding: 3px 8px;
            border-radius: 12px;
            font-size: 12px;
            font-weight: 500;
        }
        .btn-outline-primary {
            font-size: 12px;
            padding: 2px 8px;
        }
    `;
    
    // 移除之前的样式并添加新样式
    const existingStyle = document.getElementById('eu-commission-results-style');
    if (existingStyle) {
        existingStyle.remove();
    }
    style.id = 'eu-commission-results-style';
    document.head.appendChild(style);
}

// 添加日志
function addLog(message, type = 'info') {
    if (!logContainer) return;
    
    const timestamp = new Date().toLocaleTimeString();
    const logEntry = document.createElement('div');
    logEntry.className = `log-entry log-${type}`;
    
    const icon = {
        'info': 'ℹ️',
        'success': '✅',
        'warning': '⚠️',
        'error': '❌'
    }[type] || 'ℹ️';
    
    logEntry.innerHTML = `
        <span class="log-time">[${timestamp}]</span>
        <span class="log-icon">${icon}</span>
        <span class="log-message">${message}</span>
    `;
    
    logContainer.appendChild(logEntry);
    logContainer.scrollTop = logContainer.scrollHeight;
    
    // 限制日志条数
    const maxLogs = 100;
    while (logContainer.children.length > maxLogs) {
        logContainer.removeChild(logContainer.firstChild);
    }
}

// 清空日志
function clearEuCommissionLog() {
    if (logContainer) {
        logContainer.innerHTML = '';
        addLog('日志已清空', 'info');
    }
}

// 导出函数供全局使用
window.euCommissionFunctions = {
    init: initEuCommission,
    start: startEuCommissionScraping,
    stop: stopEuCommissionScraping,
    export: exportEuCommissionResults,
    clearLog: clearEuCommissionLog
};

// 页面加载完成后自动初始化
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initEuCommission);
} else {
    initEuCommission();
}

// 添加窗口关闭时的处理
window.addEventListener('beforeunload', async (event) => {
    if (isScrapingActive && abortController) {
        // 阻止默认的关闭行为
        event.preventDefault();
        event.returnValue = '抓取任务正在进行中，关闭窗口将中断任务并保存已获取的数据。确定要关闭吗？';
        
        // 发送中断信号
        try {
            console.log('窗口关闭时发送中断信号');
            abortController.abort();
        } catch (error) {
            console.error('窗口关闭时停止抓取失败:', error);
        }
    }
});

// 添加页面隐藏时的处理（用户切换标签页或最小化窗口）
window.addEventListener('visibilitychange', () => {
    if (document.hidden && isScrapingActive) {
        console.log('页面被隐藏，抓取任务继续在后台运行');
        addLog('页面被隐藏，抓取任务继续在后台运行', 'info');
    }
});

console.log('EU Commission 模块加载完成');